import { useState, useEffect } from 'react';
import { Button, Input, Label, Text, Spinner, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose } from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';
import { AuditLogService, AuditAction } from '@packages/shared';

// 权限配置接口
interface Permission {
  id: string;
  name: string;
  description: string;
  category: string;
  isEnabled: boolean;
  createdAt: string;
}

// 权限分类
const permissionCategories = [
  { id: 'user', name: '用户管理', description: '用户相关的权限' },
  { id: 'audit', name: '审计日志', description: '审计日志相关的权限' },
  { id: 'system', name: '系统设置', description: '系统配置相关的权限' },
  { id: 'dashboard', name: '仪表板', description: '仪表板相关的权限' }
];

// 预定义权限
const defaultPermissions: Permission[] = [
  // 用户管理权限
  {
    id: 'user.create',
    name: '创建用户',
    description: '可以添加新用户到系统',
    category: 'user',
    isEnabled: true,
    createdAt: '2024-01-01'
  },
  {
    id: 'user.read',
    name: '查看用户',
    description: '可以查看用户列表和详细信息',
    category: 'user',
    isEnabled: true,
    createdAt: '2024-01-01'
  },
  {
    id: 'user.update',
    name: '编辑用户',
    description: '可以修改用户信息',
    category: 'user',
    isEnabled: true,
    createdAt: '2024-01-01'
  },
  {
    id: 'user.delete',
    name: '删除用户',
    description: '可以删除用户账号',
    category: 'user',
    isEnabled: true,
    createdAt: '2024-01-01'
  },
  {
    id: 'role.assign',
    name: '分配角色',
    description: '可以分配和修改用户角色',
    category: 'user',
    isEnabled: true,
    createdAt: '2024-01-01'
  },
  // 审计日志权限
  {
    id: 'audit.view',
    name: '查看审计日志',
    description: '可以查看系统操作日志',
    category: 'audit',
    isEnabled: true,
    createdAt: '2024-01-01'
  },
  {
    id: 'audit.export',
    name: '导出审计日志',
    description: '可以导出审计日志文件',
    category: 'audit',
    isEnabled: true,
    createdAt: '2024-01-01'
  },
  {
    id: 'audit.clean',
    name: '清理审计日志',
    description: '可以清理过期的审计日志',
    category: 'audit',
    isEnabled: true,
    createdAt: '2024-01-01'
  },
  // 系统设置权限
  {
    id: 'system.settings',
    name: '系统设置',
    description: '可以修改系统配置',
    category: 'system',
    isEnabled: true,
    createdAt: '2024-01-01'
  },
  {
    id: 'system.roles',
    name: '角色管理',
    description: '可以管理系统角色',
    category: 'system',
    isEnabled: true,
    createdAt: '2024-01-01'
  },
  {
    id: 'system.permissions',
    name: '权限管理',
    description: '可以管理系统权限',
    category: 'system',
    isEnabled: true,
    createdAt: '2024-01-01'
  },
  // 仪表板权限
  {
    id: 'dashboard.view',
    name: '查看仪表板',
    description: '可以查看系统仪表板',
    category: 'dashboard',
    isEnabled: true,
    createdAt: '2024-01-01'
  }
];

export default function PermissionManagementPage() {
  const { session } = useSession();
  const [permissions, setPermissions] = useState<Permission[]>(defaultPermissions);
  const [loading, setLoading] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [currentPermission, setCurrentPermission] = useState<Permission | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [alert, setAlert] = useState('');
  const [showAlert, setShowAlert] = useState(false);
  const [form, setForm] = useState({
    name: '',
    description: '',
    category: 'user'
  });

  // 检查权限
  const canManagePermissions = session?.userRole === 'admin';

  useEffect(() => {
    if (!canManagePermissions) {
      setAlert('您没有权限访问此页面');
      setShowAlert(true);
    }
  }, [canManagePermissions]);

  // 过滤权限
  const filteredPermissions = permissions.filter(permission => {
    const matchesSearch = permission.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         permission.description.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || permission.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  // 切换权限状态
  const togglePermissionStatus = async (permissionId: string) => {
    if (!session) return;

    setLoading(true);
    try {
      const updatedPermissions = permissions.map(permission =>
        permission.id === permissionId
          ? { ...permission, isEnabled: !permission.isEnabled }
          : permission
      );
      setPermissions(updatedPermissions);

      const permission = permissions.find(p => p.id === permissionId);
      if (permission) {
        await AuditLogService.log(
          session.userId,
          session.userName,
          session.userRole,
          AuditAction.SYSTEM_ACCESS,
          `${permission.isEnabled ? '禁用' : '启用'}权限: ${permission.name}`,
          true,
          { permissionId, newStatus: !permission.isEnabled }
        );
      }

      setAlert('权限状态更新成功');
      setShowAlert(true);
    } catch (error) {
      console.error('更新权限状态失败:', error);
      setAlert('更新失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 添加权限
  const handleAddPermission = async () => {
    if (!session) return;

    setLoading(true);
    try {
      const newPermission: Permission = {
        id: `custom.${Date.now()}`,
        name: form.name,
        description: form.description,
        category: form.category,
        isEnabled: true,
        createdAt: new Date().toISOString().split('T')[0]
      };

      setPermissions(prev => [...prev, newPermission]);

      await AuditLogService.log(
        session.userId,
        session.userName,
        session.userRole,
        AuditAction.SYSTEM_ACCESS,
        `添加权限: ${form.name}`,
        true,
        { permissionId: newPermission.id }
      );

      setShowAddDialog(false);
      setForm({ name: '', description: '', category: 'user' });
      setAlert('权限添加成功');
      setShowAlert(true);
    } catch (error) {
      console.error('添加权限失败:', error);
      setAlert('添加失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 编辑权限
  const handleEditPermission = (permission: Permission) => {
    setCurrentPermission(permission);
    setForm({
      name: permission.name,
      description: permission.description,
      category: permission.category
    });
    setShowEditDialog(true);
  };

  // 保存编辑
  const handleSaveEdit = async () => {
    if (!currentPermission || !session) return;

    setLoading(true);
    try {
      const updatedPermissions = permissions.map(permission =>
        permission.id === currentPermission.id
          ? { ...permission, name: form.name, description: form.description, category: form.category }
          : permission
      );
      setPermissions(updatedPermissions);

      await AuditLogService.log(
        session.userId,
        session.userName,
        session.userRole,
        AuditAction.SYSTEM_ACCESS,
        `编辑权限: ${form.name}`,
        true,
        { permissionId: currentPermission.id }
      );

      setShowEditDialog(false);
      setCurrentPermission(null);
      setAlert('权限更新成功');
      setShowAlert(true);
    } catch (error) {
      console.error('更新权限失败:', error);
      setAlert('更新失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 获取分类名称
  const getCategoryName = (categoryId: string) => {
    const category = permissionCategories.find(c => c.id === categoryId);
    return category ? category.name : categoryId;
  };

  if (!canManagePermissions) {
    return (
      <div className="p-6">
        <div className="text-center">
          <Text className="text-xl text-red-500">访问被拒绝</Text>
          <Text className="text-gray-500 mt-2">您没有权限访问权限管理页面</Text>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6">
      {/* 页面头部 */}
      <div className="mb-6">
        <Text className="text-2xl font-bold text-gray-900 mb-2">权限管理</Text>
        <Text className="text-gray-600">管理系统权限配置</Text>
      </div>

      {/* 提示信息 */}
      {showAlert && (
        <div className="mb-4 p-3 bg-green-100 border border-green-500 rounded shadow-sm">
          <Text className="font-semibold text-green-700">{alert}</Text>
        </div>
      )}

      {/* 操作栏 */}
      <div className="bg-white rounded-lg shadow p-4 mb-6">
        <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
          <div className="flex flex-col sm:flex-row gap-4 flex-1">
            <div className="flex-1 max-w-md">
              <Input
                placeholder="搜索权限..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full"
              />
            </div>
            <div>
              <select
                className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
              >
                <option value="all">所有分类</option>
                {permissionCategories.map(category => (
                  <option key={category.id} value={category.id}>
                    {category.name}
                  </option>
                ))}
              </select>
            </div>
            <div className="text-sm text-gray-500">
              共 {filteredPermissions.length} 个权限
            </div>
          </div>
          <Button
            variant="primary"
            onClick={() => setShowAddDialog(true)}
          >
            添加权限
          </Button>
        </div>
      </div>

      {/* 权限列表 */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-200">
          <Text className="text-lg font-semibold">系统权限</Text>
        </div>

        <div className="overflow-x-auto">
          <Table className="min-w-full">
            <TableHeader className="bg-gray-50">
              <TableRow>
                <TableHead className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  权限信息
                </TableHead>
                <TableHead className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  分类
                </TableHead>
                <TableHead className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </TableHead>
                <TableHead className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  创建时间
                </TableHead>
                <TableHead className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody className="bg-white divide-y divide-gray-200">
              {filteredPermissions.map((permission) => (
                <TableRow key={permission.id} className="hover:bg-gray-50">
                  <TableCell className="px-6 py-4 whitespace-nowrap">
                    <div>
                      <Text className="text-sm font-medium text-gray-900">
                        {permission.name}
                      </Text>
                      <Text className="text-sm text-gray-500">
                        {permission.description}
                      </Text>
                    </div>
                  </TableCell>
                  <TableCell className="px-6 py-4 whitespace-nowrap">
                    <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">
                      {getCategoryName(permission.category)}
                    </span>
                  </TableCell>
                  <TableCell className="px-6 py-4 whitespace-nowrap">
                    <span
                      className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                        permission.isEnabled
                          ? 'bg-green-100 text-green-800'
                          : 'bg-red-100 text-red-800'
                      }`}
                    >
                      {permission.isEnabled ? '启用' : '禁用'}
                    </span>
                  </TableCell>
                  <TableCell className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {permission.createdAt}
                  </TableCell>
                  <TableCell className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex space-x-2">
                      <Button
                        size="sm"
                        onClick={() => handleEditPermission(permission)}
                        variant="outline"
                      >
                        编辑
                      </Button>
                      <Button
                        size="sm"
                        onClick={() => togglePermissionStatus(permission.id)}
                        variant={permission.isEnabled ? 'danger' : 'primary'}
                        disabled={loading}
                      >
                        {permission.isEnabled ? '禁用' : '启用'}
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>

        {filteredPermissions.length === 0 && (
          <div className="text-center py-12 text-gray-500">
            <Text className="text-lg font-medium">暂无权限数据</Text>
            <Text className="text-sm">当前搜索条件下没有找到权限</Text>
          </div>
        )}
      </div>

      {/* 添加权限对话框 */}
      <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
        <DialogContent size="md">
          <DialogHeader>
            <DialogTitle>添加权限</DialogTitle>
            <DialogDescription>创建新的系统权限</DialogDescription>
          </DialogHeader>

          <div className="py-4 space-y-4">
            <div>
              <Label htmlFor="add-name">权限名称</Label>
              <Input
                id="add-name"
                value={form.name}
                onChange={(e) => setForm(prev => ({ ...prev, name: e.target.value }))}
                placeholder="请输入权限名称"
                className="mt-1"
              />
            </div>
            <div>
              <Label htmlFor="add-description">权限描述</Label>
              <Input
                id="add-description"
                value={form.description}
                onChange={(e) => setForm(prev => ({ ...prev, description: e.target.value }))}
                placeholder="请输入权限描述"
                className="mt-1"
              />
            </div>
            <div>
              <Label htmlFor="add-category">权限分类</Label>
              <select
                id="add-category"
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                value={form.category}
                onChange={(e) => setForm(prev => ({ ...prev, category: e.target.value }))}
              >
                {permissionCategories.map(category => (
                  <option key={category.id} value={category.id}>
                    {category.name}
                  </option>
                ))}
              </select>
            </div>
          </div>

          <DialogFooter>
            <DialogClose>取消</DialogClose>
            <Button 
              variant="primary" 
              onClick={handleAddPermission}
              disabled={loading || !form.name || !form.description}
            >
              {loading ? <Spinner size="sm" className="mr-2" /> : null}
              添加权限
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 编辑权限对话框 */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent size="md">
          <DialogHeader>
            <DialogTitle>编辑权限</DialogTitle>
            <DialogDescription>修改权限信息</DialogDescription>
          </DialogHeader>

          <div className="py-4 space-y-4">
            <div>
              <Label htmlFor="edit-name">权限名称</Label>
              <Input
                id="edit-name"
                value={form.name}
                onChange={(e) => setForm(prev => ({ ...prev, name: e.target.value }))}
                placeholder="请输入权限名称"
                className="mt-1"
              />
            </div>
            <div>
              <Label htmlFor="edit-description">权限描述</Label>
              <Input
                id="edit-description"
                value={form.description}
                onChange={(e) => setForm(prev => ({ ...prev, description: e.target.value }))}
                placeholder="请输入权限描述"
                className="mt-1"
              />
            </div>
            <div>
              <Label htmlFor="edit-category">权限分类</Label>
              <select
                id="edit-category"
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                value={form.category}
                onChange={(e) => setForm(prev => ({ ...prev, category: e.target.value }))}
              >
                {permissionCategories.map(category => (
                  <option key={category.id} value={category.id}>
                    {category.name}
                  </option>
                ))}
              </select>
            </div>
          </div>

          <DialogFooter>
            <DialogClose>取消</DialogClose>
            <Button 
              variant="primary" 
              onClick={handleSaveEdit}
              disabled={loading || !form.name || !form.description}
            >
              {loading ? <Spinner size="sm" className="mr-2" /> : null}
              保存修改
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
